package com.wang.util;

import com.wang.thread.SetTokenTimer;

import java.util.LinkedList;
import java.util.UUID;

/**
 * 令牌桶算法
 * Created by wang on 2017/5/3.
 */
public class TokenBucket {
    private static final LinkedList<UUID> list = new LinkedList<>();

    public static void setToken() {
        if (list.size()<100)
        list.addLast(UUID.randomUUID());
    }

    public static boolean getToken() {
        synchronized (list) {
            if (list.size() == 0)
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
        UUID uuid= list.poll();
        return uuid != null;
    }

    //开启存放令牌线程
    public static void startSetTokenTimer(){
        Thread thread = new Thread(new SetTokenTimer(list));
        thread.start();
    }

    //获取令牌数量
    public static int getTokenNum(){
        return list.size();
    }

}
